package com.cxz.food.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginInterceptor extends HandlerInterceptorAdapter {

    Logger logger = LoggerFactory.getLogger(LoginInterceptor    .class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        logger.info("------preHandle------");
        //获取session
        HttpSession session = httpServletRequest.getSession(true);
        //判断用户ID是否存在，不存在就跳转到登录界面
        Integer businessId = (Integer) session.getAttribute("businessId");
        if(businessId == null){
            logger.info("------:跳转到login页面！");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/user/login");
            return false;
        }else{
            session.setAttribute("businessId", session.getAttribute("businessId"));
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
